package util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import sun.misc.BASE64Encoder;
import util.Alibb.AsyncDemo;
import util.Alibb.Entity.Ali_Config;
import util.Alibb.Entity.Ali_Date;
import util.Alibb.Entity.Ali_Input;
import util.Alibb.Entity.Ali_Inputs;
import util.Alibb.SyncDemo;

import javax.imageio.stream.FileImageInputStream;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LiceneseRecenise {

    public static void main(String[] args){

//        AsyncDemo asyncDemo = new AsyncDemo();
//        byte[] data = null;
//        File file = new File("e:\\1.jpg");
//        try {
//            FileImageInputStream input = new FileImageInputStream(file);
//            ByteArrayOutputStream output = new ByteArrayOutputStream();
//            byte[] buf = new byte[1024];
//            int numBytesRead = 0;
//            while ((numBytesRead = input.read(buf)) != -1) {
//                output.write(buf, 0, numBytesRead);
//            }
//            data = output.toByteArray();
//            output.close();
//            input.close();
//            asyncDemo.数据服务_5_13_车牌识别Demo(data);

        String host = "http://ocrcp.market.alicloudapi.com";
        String path = "/rest/160601/ocr/ocr_vehicle_plate.json";
        String method = "POST";
        String appcode = "27cd73ec565f42248bad3bae2825b6c1";
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/json; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();

        Ali_Config config = new Ali_Config();
        config.setMulti_crop(false);

        Ali_Date date1 = new Ali_Date();
        date1.setDataType(50);
        String image = GetImageStr();
        System.out.println(image);
        date1.setDataValue(image);

        Ali_Date date2 = new Ali_Date();
        date2.setDataType(50);
        date2.setDataValue(JSON.toJSONString(config));
        Ali_Input input = new Ali_Input();
        input.setConfigure(date2);
        input.setImage(date1);

        Ali_Inputs inputs = new Ali_Inputs();
        List<Ali_Input> list = new ArrayList<Ali_Input>();
        list.add(input);
        inputs.setInputs(list);

        String bodys = JSON.toJSONString(inputs);
        System.out.println(bodys);

        sendPost("http://ocrcp.market.alicloudapi.com/rest/160601/ocr/ocr_vehicle_plate.json",bodys);
//        HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
//        System.out.println(response.toString());
        try {

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // 图片转化成base64字符串
    public static String GetImageStr() {
        // 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        String imgFile = "e://2.jpg";
        InputStream in = null;
        byte[] data = null;
        // 读取图片字节数组
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        // 返回Base64编码过的字节数组字符串
        return encoder.encode(data);
    }

    private static final Logger LOGGER = LogManager.getLogger(LiceneseRecenise.class);

    public static String sendPost(String url,String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {

//            String param = "";
            LOGGER.info(param);
            URL realUrl = new URL(url);
            LOGGER.warn("12======"+realUrl);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/octet-stream; charset=utf-8");
            conn.setRequestProperty("Authorization","APPCODE 27cd73ec565f42248bad3bae2825b6c1");

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            System.out.println("123======="+result);
        } catch (Exception e) {

            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        LOGGER.info("返回结果是："+result);
        return result;
    }

}
